﻿using System.Linq;
using Microsoft.EntityFrameworkCore;
using Abp.Authorization;
using Abp.Authorization.Roles;
using Abp.Authorization.Users;
using Abp.MultiTenancy;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using AbpProjectTemplate.Domain.Users.Admins;
using AbpProjectTemplate.Domain.Roles;

namespace AbpProjectTemplate.EntityFrameworkCore.Seed.Host
{
    public class HostRoleAndUserCreator
    {
        private readonly AppDbContext _context;

        public HostRoleAndUserCreator(AppDbContext context)
        {
            this._context = context;
        }

        public void Create()
        {
            this.CreateHostRoleAndUsers();
        }

        private void CreateHostRoleAndUsers()
        {
            // Admin role for host

            var adminRoleForHost = this._context.Roles.IgnoreQueryFilters()
                .Include(t=>t.Permissions)
                .FirstOrDefault(r => r.TenantId == null && r.Name == AppRoleConfig.AdminRoleName);
            if (adminRoleForHost == null)
            {
                adminRoleForHost = AppRoleConfig.CreateAdminRole();
                this._context.Roles.Add(adminRoleForHost);
                this._context.SaveChanges();
            }

            // Admin user for host

            var adminUserForHost = this._context.Users.IgnoreQueryFilters().FirstOrDefault(u => u.TenantId == null && u.UserName == AbpUserBase.AdminUserName);
            if (adminUserForHost == null)
            {
                var user = Admin.CreateDefaultAdmin(null);

                adminUserForHost = this._context.Users.Add(user).Entity;
                this._context.SaveChanges();

                // Assign Admin role to admin user
                this._context.UserRoles.Add(new UserRole(null, adminUserForHost.Id, adminRoleForHost.Id));
                this._context.SaveChanges();
            }
        }
    }
}

